<template>
  <div>
    <!-- 搜索框 -->
    <div id="nav-head">
      <div class="left">
        <van-icon name="arrow-left" size="22" @click="back"/>
      </div>
      <div class="center">
        <van-search type="text" v-model="text" placeholder="满58包邮！输入关键字搜索" background="#409EFF" shape="round" @search="toSearch"/>
      </div>
      <div class="right">
        <van-button color="#409EFF" @click="toSearch" round>搜索</van-button>
      </div>
    </div>
    <!-- 搜索框 -->
    <!-- 搜索历史纪录 -->
    <ul class="history">
      <li v-for="item in histories " :key="item" @click="hisSearch(item)">{{item}}</li>
    </ul>
    <!-- 搜索历史纪录 -->
  </div>
</template>

<script>
export default {
  name: 'HomeHead',
  data () {
    return {
      text: '',
      histories: localStorage.getItem('search')
        ? JSON.parse(localStorage.getItem('search'))
        : []// 搜索历史记录 如果没有历史记录就为空数组，防止报错
    }
  },
  methods: {
    // 点击搜素记录搜索
    hisSearch (item) {
      this.text = item
      this.toSearch()
    },
    // 点击搜索框进入搜索页，将事件处理发送给父组件
    toSearch () {
      // 此处存在bug，搜索记录为空时，第一项为空，会被条件渲染
      // 加入搜索记录之前先取搜素记录，进行去重
      let arr = localStorage.getItem('search') ? JSON.parse(localStorage.getItem('search')) : []
      // 将最新的记录放在最前
      arr.unshift(this.text)
      // 去重
      arr = [...new Set(arr)]
      arr = arr.slice(0, 10)
      // 缓存搜索记录
      localStorage.setItem('search', JSON.stringify(arr))
      this.$router.push({
        path: '/searchList',
        query: {
          k: this.text
        }
      })
    },
    // 跳转到登录页
    back () {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
#nav-head {
  font-size: 0.3rem;
  background-color: #409EFF;
  position: fixed;
  z-index: 9;
  width: 100%;
  display: flex;
  align-items: center;
  .left,.right {
    background-color: #409EFF;
    flex: 2;
    text-align: center;
    color: #fff;
  }
  .left {
    flex: 1
  }
  .center{
    flex: 9
  }
}
.history {
  padding-top: 1.8rem;
  display: flex;
  flex-wrap: wrap;
  font-size: 0.24rem;
  li {
    margin: 0.2rem;
    line-height: 0.4rem;
    background: rgb(248, 248, 248);
    color: rgb(85, 85, 85);
    border-radius: 0.3333rem;
    padding: 0.2rem 0.26rem;
  }
}
</style>
